﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Practice2___DispatchHelper.Model;

namespace Practice2___DispatchHelper.Common
{
    public class CreateUserInfoHelper
    {
        /// <summary>
        /// 执行进度通知事件
        /// </summary>
        public event EventHandler<CreateArgs> CreateProgress;
        /// <summary>
        /// 需要创建的信息
        /// </summary>
        public UserParam user { get; set; }

        public CreateUserInfoHelper(UserParam user)
        {
            this.user = user;
        }

        /// <summary>
        /// 开启线程
        /// </summary>
        public void CreateThread()
        {
            Thread t = new Thread(ThreadHandler);
            t.Start();
        }

        /// <summary>
        /// 线程服务函数
        /// </summary>
        private void ThreadHandler()
        {
            try
            {
                // 执行耗时任务并通知处理进度
                for (int i = 0; i <= 10; i++)
                {
                    CreateProgress?.Invoke(this, new CreateArgs()
                    {
                        IsFinish = i == 10 ? true : false,
                        Progress = i * 10,
                        UserParam = null
                    });

                    Thread.Sleep(1000);
                }

                CreateProgress?.Invoke(this, new CreateArgs()
                {
                    IsFinish = true,
                    Progress = 100,
                    UserParam = user
                });
            }
            catch (Exception)
            {
                CreateProgress?.Invoke(this, new CreateArgs()
                {
                    IsFinish = true,
                    Progress = 100,
                    UserParam = null
                });
            }
        }

        public class CreateArgs : EventArgs
        {
            /// <summary>
            /// 是否创建结束
            /// </summary>
            public bool IsFinish { get; set; }
            /// <summary>
            /// 完成进度
            /// </summary>
            public int Progress { get; set; }
            /// <summary>
            /// 处理后的用户信息
            /// </summary>
            public UserParam UserParam { get; set; }
        }
    }
}
